#coding: utf-8

import os
import cgi
import web
import time
import uuid
import Image
import datetime
from web import form

import db
import skate as s
from config import DIR
from libs import *

cgi.maxlen = 512 * 1024 # Maximum upload file size: 512Kb

__all__ = ['news', 'map', 'profile', 'users']

class news:
    
    def GET(self):
        _news = s.db.select('news', order="atime DESC", limit=20)

        news = []
        for i in _news:
            tmp = {}
            tmp['id'] = i['id']
            tmp['uid'] = i['uid']
            tmp['type'] = i['type']
            tmp['atime'] = i['atime']
            (tmp['nickname'], tmp['tiny_avatar']) = db.get_user_baseinfo(i['uid'])
            
            assert(i['type'] <= 7)

            try:
                if i['type'] == NEWS['newuser']:
                    pass
                elif i['type'] == NEWS['avatar']:
                    tmp['tiny_avatar'] = db.get_pic_path(i['ava'])
                elif i['type'] == NEWS['newact']:
                    tmp['aid'] = i['aid']
                    tmp['subject'] = db.get_actsubject(i['aid'])
                elif i['type'] == NEWS['relation']:
                    rel = s.db.select('relation', where="id=%d" % i['rid'])[0]
                    tmp['subject'] = db.get_actsubject(rel['aid'])
                    tmp['aid'] = rel['aid']
                    tmp['relation'] = rel['relation']
                elif i['type'] == NEWS['newthread']:
                    td = db.get_thread_detail(i['tid'])
                    tmp['act_subject'] = td['activity']
                    tmp['tid'] = i['tid']
                    tmp['aid'] = td['aid']
                    tmp['th_subject'] = td['subject']
                elif i['type'] == NEWS['newpost']:
                    td = db.get_thread_detail(i['tid'])
                    tmp['tid'] = i['tid']
                    tmp['aid'] = td['aid']
                    tmp['act_subject'] = td['activity']
                    tmp['th_subject'] = td['subject']
            except:
                raise

            news.append(tmp)

        return s.render.news(news)

class map:

    def __get_acts(self):
        acts = db.get_limit_update_acts(limit=15)
        return recover_datetime(acts)

    def GET(self):
        acts = self.__get_acts()
        return s.render.map(acts)


class profile:
    
    def GET(self):
        input = web.input(uid=None)
        try:
            uid = int(input.uid)
            user = db.get_user(uid)
            own_acts = recover_datetime(db.get_own_acts(uid, limit=5))
            wish_acts = recover_datetime(db.get_user_wish_acts(uid, limit=5))
            do_acts = recover_datetime(db.get_user_do_acts(uid, limit=5))

            own_size = len(own_acts)
            wish_size = len(wish_acts)
            do_size = len(do_acts)

            threads = db.get_threads(uid=uid)
            th_size = len(threads)

            if s.session.id == uid:
                username = '我'
            else:
                if user['gender'] == 0:
                    username = '她'
                else:
                    username = '他'
        except:
            raise
            raise web.notfound()
        else:
            return s.render.profile(user, own_acts[:5], wish_acts[:5], do_acts[:5],
                    own_size, wish_size, do_size, threads[:5], th_size, username)

class users:
    def GET(self):
        pass

class avatar:

    avatar_form = form.Form(
            form.File('avatar', description='你的头像'),
            )

    def _resize(self, imgpath):
        origin_name = os.path.basename(imgpath)
        origin_dir = os.path.dirname(imgpath)

        origin_img = Image.open(imgpath)
        x, y = origin_img.size
        if x > y: x = y

        tiny_img = origin_img.crop((0, 0, x, x))
        tiny_img = tiny_img.resize(TINY_AVATAR_SIZE, Image.ANTIALIAS)

        tiny_name = "tiny-%s" % origin_name
        tiny_img.save(os.path.join(origin_dir, tiny_name))

        return tiny_name

    def GET(self):
        avatar_path = db.get_avatar(s.session.id)

        f = self.avatar_form()
        return s.render.avatar(f, avatar_path)

    def POST(self):
        avatar_path = db.get_avatar(s.session.id)

        try:
            x = web.input(avatar={})
        except ValueError:
            s.session.show_msg = True
            s.session.msg = "图片太大, 请选择小于512Kb的图片作为头像"
            return web.seeother("avatar")

        s.session.show_msg = True
        if x.avatar.filename:
            
            picname = os.path.basename(x.avatar.filename)
            tiny_picname = 'tiny-%s' % picname

            month_dir = datetime.datetime.now().strftime(
                    '%Y/%m/%d')

            avatar_dir = get_avatar_dir()
            newname = str(uuid.uuid1()) + ".jpg" # XXX danger...

            realpath = os.path.join(avatar_dir, month_dir, newname)
            verify_dir(os.path.dirname(realpath))
            # get path /var/www/0106666/static/avatar/xxx-xxx-xxx-xxx.jpg

            open(realpath, 'w').write(x.avatar.file.read())

            webpath = os.path.normpath(os.path.join(
                    '/', DIR.avatar, month_dir, newname
                    ))
            # get /static/xxx-xxx-xxx-xxx.jpg, for web browser

            tiny_webpath = os.path.normpath(os.path.join(
                    "/", DIR.avatar, month_dir, self._resize(realpath)
                    ))

            picid = db.new_avatar(s.session.id, webpath, picname)
            tiny_picid = db.new_tiny_avatar(s.session.id, tiny_webpath, tiny_picname)

            newsid = db.new_news(NEWS['avatar'], uid=s.session.id, ava=tiny_picid)

            s.session.msg = "修改头像成功"
        else:
            s.session.msg = "修改头像失败"

        return web.seeother("avatar")

class passwd:

    passwd_form = form.Form(
            form.Password('old_passwd', vpass, description='原密码'),
            form.Password('passwd', vpass, description='新密码'),
            form.Password('passwd2', vpass, description='再输一次'),
            form.Button('submit', type='submit', description='确认修改密码'),
            validators = [
                form.Validator("两次输入密码不一致", lambda i:
                    i.passwd == i.passwd2),
                form.Validator('原密码错误', lambda i:
                    len(s.db.select('user', where='id="%d" and password="%s"' % (
                        s.session.id, i.old_passwd))) > 0)
                    ]
            )

    def GET(self):
        f = self.passwd_form()
        return s.render.passwd(f)

    def POST(self):
        f = self.passwd_form()

        s.session.show_msg = True
        if not f.validates():
            s.session.msg = "修改密码失败"
            return s.render.passwd(f)

        reqid = db.update_passwd(s.session.id, f['passwd'].value)
        s.session.msg = "密码修改成功"

        return web.seeother("setting")

class setting:

    GENDER = ((0, '女'), (1, '男'))

    setting_form = form.Form(
            form.Textbox('nickname', form.notnull, description='名号'),
            form.Dropdown('location', LOCATION, description='居住在'),
            form.Textbox('location_detail', form.notnull, description=""),
            form.Textbox('age', vnum, description='年龄'),
            form.Dropdown('gender', GENDER, description='性别'),
            form.Button('submit', type='submit', description='signup'),
            )

    def ERROR(self):
        s.session.show_msg = True
        s.session.msg = "操作错误"
        raise web.notfound()

    def GET(self):
        try:
            avatar_path = db.get_avatar(s.session.id)
            user = db.get_user(s.session.id)
        except IndexError:
            self.ERROR()

        f = self.setting_form()
        f.nickname.value = user['nickname']
#         f.location_detail.value = user['location'][2:]
        f.age.value = user['age']
        f.gender.value = user['gender']
        return s.render.setting(f, avatar_path)

    def POST(self):
        avatar_path = db.get_avatar(s.session.id)

        f = self.setting_form()
        if not f.validates():
            s.session.show_msg = True
            s.session.msg = "输入不正确，更新失败"
            return s.render.setting(f, avatar_path)

        else:
            reqid = db.update_user(s.session.id, 
                    f['nickname'].value,
                    f['location'].value + f['location_detail'].value,
                    f['age'].value, f['gender'].value
                    )
            
            s.session.show_msg = True
            s.session.msg = "修改个人信息成功"
            web.seeother("profile?uid=%d" % s.session.id)

